package com.jnu.HomeworkApplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class EditBookActivity extends AppCompatActivity {

    private int returnImageId = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_book);

        Button ButtonOk = findViewById(R.id.book_ok);
        Button ButtonCancel = findViewById(R.id.book_cancel);
        EditText editText = findViewById(R.id.Book_name);

        RadioGroup bookGroup = findViewById(R.id.book_button_group);
        RadioButton book1 = findViewById(R.id.book_1_button);
        RadioButton book2 = findViewById(R.id.book_2_button);
        RadioButton book3 = findViewById(R.id.book_no_name_button);


        Intent intent = getIntent();
        String name = intent.getStringExtra("Book_Name");
        int bookImage = intent.getIntExtra("Book_id",0);
        if(name != null){
            editText.setText(name);
        }
        if(bookImage != 0){
            switch (bookImage) {
                case R.drawable.book_1:
                    book1.setChecked(true);
                    break;
                case R.drawable.book_2:
                    book2.setChecked(true);
                    break;
                case R.drawable.book_no_name:
                    book3.setChecked(true);
                    break;
            }
        }

        bookGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (book1.isChecked()){
                returnImageId = R.drawable.book_1;
            }
            else if (book2.isChecked()){
                returnImageId = R.drawable.book_2;
            }
            else if (book3.isChecked()){
                returnImageId = R.drawable.book_no_name;
            }
        });

        ButtonOk.setOnClickListener(v -> {
            int position = intent.getIntExtra("position",0);
            if(returnImageId == 0) {
                Toast.makeText(EditBookActivity.this, "请选择图片", Toast.LENGTH_LONG).show();
                return;
            }
            intent.putExtra("Book_Name",editText.getText().toString());
            intent.putExtra("Book_id",returnImageId);
            intent.putExtra("position",position);
            setResult(514,intent);
            EditBookActivity.this.finish();
        });

        ButtonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(414,intent);
                EditBookActivity.this.finish();
            }
        });
    }
}